<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>批次管理</span>
        </div>
      </template>
      
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="批次号" prop="batchCode">
          <el-input
            v-model="queryParams.batchCode"
            placeholder="请输入批次号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="批次状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择批次状态" clearable>
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['qep:production:batch:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['qep:production:batch:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['qep:production:batch:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Search"
            @click="goToQuery"
            v-hasPermi="['qep:production:batch:query']"
          >批次查询</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['qep:production:batch:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="batchList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="批次号" align="center" prop="batchCode" />
        <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
        <el-table-column label="计划数量" align="center" prop="plannedQuantity" />
        <el-table-column label="实际数量" align="center" prop="actualQuantity" />
        <el-table-column label="计划日期" align="center" prop="plannedDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.plannedDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际日期" align="center" prop="actualDate" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.actualDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批次状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="getBatchStatusType(scope.row.status)">
              {{ getBatchStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="质量状态" align="center" prop="qualityStatus">
          <template #default="scope">
            <el-tag :type="getQualityStatusType(scope.row.qualityStatus)">
              {{ getQualityStatusText(scope.row.qualityStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button 
              link type="primary" 
              icon="View" 
              @click="handleView(scope.row)"
              v-hasPermi="['qep:production:batch:query']"
            >查看</el-button>
            <el-button 
              link type="primary" 
              icon="Edit" 
              @click="handleUpdate(scope.row)" 
              v-hasPermi="['qep:production:batch:edit']"
              v-if="['PLANNED', 'IN_PROGRESS'].includes(scope.row.status)"
            >修改</el-button>
            <el-button 
              link type="primary" 
              icon="Promotion" 
              @click="handleProcess(scope.row)" 
              v-hasPermi="['qep:production:process:flow']"
            >工序</el-button>
            <el-button 
              link type="primary" 
              icon="Delete" 
              @click="handleDelete(scope.row)" 
              v-hasPermi="['qep:production:batch:remove']"
              v-if="scope.row.status === 'PLANNED'"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改批次对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="batchForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchCode">
              <el-input v-model="form.batchCode" placeholder="请输入批次号" :disabled="form.id !== undefined" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select v-model="form.productId" placeholder="请选择产品">
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划数量" prop="plannedQuantity">
              <el-input-number v-model="form.plannedQuantity" :min="1" :max="10000" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际数量" prop="actualQuantity">
              <el-input-number v-model="form.actualQuantity" :min="0" :max="10000" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划日期" prop="plannedDate">
              <el-date-picker
                v-model="form.plannedDate"
                type="date"
                placeholder="选择计划日期"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际日期" prop="actualDate">
              <el-date-picker
                v-model="form.actualDate"
                type="date"
                placeholder="选择实际日期"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择批次状态">
                <el-option
                  v-for="dict in statusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质量状态" prop="qualityStatus">
              <el-select v-model="form.qualityStatus" placeholder="请选择质量状态">
                <el-option
                  v-for="dict in qualityStatusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from '@/utils/ruoyi'
// 注释掉原有API导入
// import { listBatch, getBatch, delBatch, addBatch, updateBatch, exportBatch } from '@/api/qep/production'
// import { listProduct } from '@/api/qep/product'
// 导入mock数据
import { batchManagementMockData } from '@/mock/production'

const router = useRouter()

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 批次表格数据
const batchList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 日期范围
const dateRange = ref([])
// 产品选项
const productOptions = ref([])
// 批次状态选项
const statusOptions = ref([])
// 质量状态选项
const qualityStatusOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  batchCode: undefined,
  productName: undefined,
  status: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  batchCode: undefined,
  productId: undefined,
  plannedQuantity: 0,
  actualQuantity: 0,
  plannedDate: undefined,
  actualDate: undefined,
  status: 'PLANNED',
  qualityStatus: 'PENDING',
  remark: undefined
})

// 表单校验
const rules = reactive({
  batchCode: [
    { required: true, message: "批次号不能为空", trigger: "blur" }
  ],
  productId: [
    { required: true, message: "产品不能为空", trigger: "change" }
  ],
  plannedQuantity: [
    { required: true, message: "计划数量不能为空", trigger: "blur" }
  ],
  plannedDate: [
    { required: true, message: "计划日期不能为空", trigger: "blur" }
  ]
})

// 获取批次状态类型
const getBatchStatusType = (status) => {
  switch (status) {
    case 'PLANNED': return 'info'
    case 'IN_PROGRESS': return 'primary'
    case 'COMPLETED': return 'success'
    case 'DELAYED': return 'danger'
    case 'CANCELLED': return 'warning'
    default: return ''
  }
}

// 获取批次状态文本
const getBatchStatusText = (status) => {
  const statusMap = {
    'PLANNED': '计划中',
    'IN_PROGRESS': '生产中',
    'COMPLETED': '已完成',
    'DELAYED': '已延期',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 获取质量状态类型
const getQualityStatusType = (status) => {
  switch (status) {
    case 'PENDING': return 'info'
    case 'PASSED': return 'success'
    case 'FAILED': return 'danger'
    case 'PARTIAL': return 'warning'
    default: return ''
  }
}

// 获取质量状态文本
const getQualityStatusText = (status) => {
  const statusMap = {
    'PENDING': '待检',
    'PASSED': '合格',
    'FAILED': '不合格',
    'PARTIAL': '部分合格'
  }
  return statusMap[status] || status
}

// 使用mock数据获取选项
const getOptions = () => {
  productOptions.value = batchManagementMockData.productOptions;
  statusOptions.value = batchManagementMockData.statusOptions;
  qualityStatusOptions.value = batchManagementMockData.qualityStatusOptions;
}

// 使用mock数据获取批次列表
const getList = () => {
  loading.value = true;
  
  // 模拟API调用延迟
  setTimeout(() => {
    // 过滤数据
    let filteredData = [...batchManagementMockData.batchList];
    
    // 应用查询条件
    if (queryParams.batchCode) {
      filteredData = filteredData.filter(item => 
        item.batchCode.toLowerCase().includes(queryParams.batchCode.toLowerCase())
      );
    }
    
    if (queryParams.productName) {
      filteredData = filteredData.filter(item => 
        item.productName.toLowerCase().includes(queryParams.productName.toLowerCase())
      );
    }
    
    if (queryParams.status) {
      filteredData = filteredData.filter(item => item.status === queryParams.status);
    }
    
    if (dateRange.value && dateRange.value.length === 2) {
      const startDate = new Date(dateRange.value[0]).getTime();
      const endDate = new Date(dateRange.value[1]).getTime();
      
      filteredData = filteredData.filter(item => {
        const itemDate = new Date(item.plannedDate).getTime();
        return itemDate >= startDate && itemDate <= endDate;
      });
    }
    
    // 计算分页
    const start = (queryParams.pageNum - 1) * queryParams.pageSize;
    const end = start + queryParams.pageSize;
    
    // 设置总数和分页数据
    total.value = filteredData.length;
    batchList.value = filteredData.slice(start, end);
    
    loading.value = false;
  }, 500);
}

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
}

// 表单重置
const reset = () => {
  form.id = undefined;
  form.batchCode = undefined;
  form.productId = undefined;
  form.plannedQuantity = 0;
  form.actualQuantity = 0;
  form.plannedDate = undefined;
  form.actualDate = undefined;
  form.status = 'PLANNED';
  form.qualityStatus = 'PENDING';
  form.remark = undefined;
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = [];
  queryParams.batchCode = undefined;
  queryParams.productName = undefined;
  queryParams.status = undefined;
  handleQuery();
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 新增按钮操作
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加批次";
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset();
  const id = row.id || ids.value[0];
  
  // 模拟获取单个批次数据
  const batchData = batchManagementMockData.batchList.find(item => item.id === id);
  
  if (batchData) {
    // 复制数据到表单
    Object.assign(form, batchData);
    
    // 查找产品ID
    if (batchData.productName) {
      const product = productOptions.value.find(p => p.name === batchData.productName);
      if (product) {
        form.productId = product.id;
      }
    }
    
    open.value = true;
    title.value = "修改批次";
  }
}

// 提交按钮
const submitForm = () => {
  // 模拟表单提交
  setTimeout(() => {
    if (form.id) {
      // 更新操作
      ElMessage.success("修改成功");
    } else {
      // 新增操作
      ElMessage.success("新增成功");
    }
    open.value = false;
    getList();
  }, 500);
}

// 删除按钮操作
const handleDelete = (row) => {
  const batchIds = row.id || ids.value;
  
  ElMessageBox.confirm('是否确认删除批次编号为"' + batchIds + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    // 模拟删除操作
    setTimeout(() => {
      ElMessage.success("删除成功");
      getList();
    }, 500);
  }).catch(() => {});
}

// 导出按钮操作
const handleExport = () => {
  ElMessageBox.confirm('是否确认导出所有批次数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    ElMessage.success("导出成功");
  }).catch(() => {});
}

// 查看按钮操作
const handleView = (row) => {
  router.push({ path: '/production/batch/detail', query: { batchCode: row.batchCode } });
}

// 工序按钮操作
const handleProcess = (row) => {
  router.push({ path: '/production/process/flow', query: { batchCode: row.batchCode } });
}

// 跳转到批次查询页面
const goToQuery = () => {
  router.push({ path: '/production/batch/query' });
}

onMounted(() => {
  // 获取选项数据
  getOptions();
  
  // 获取批次列表
  getList();
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 